package com.langfeiyes.pattern.composite;


import java.util.ArrayList;
import java.util.List;

/**
 * 组合节点，包含其他叶子节点/子组合节点
 * 只实现Composite 方法
 */
public class Composite extends Component{

    private List<Component> children = new ArrayList<>();
    @Override
    public void operation() {
        System.out.println("我是组合节点");
        for (Component child : children) {
            //需要时需要递归执行
            System.out.print(" ");
            child.operation();
        }
    }

    //需要重写组合节点自己方法
    @Override
    public void addChild(Component child) {
       if(child != null){
           children.add(child);
       }

    }

    @Override
    public void removeChild(Component child) {
        if(child != null){
            children.remove(child);
        }
    }

    @Override
    public Component getChild(int index) {

        if(index >= 0 && index < children.size()){
            return  children.get(index);
        }
        return null;
    }
}
